'''
Author: duliang thinktanker@163.com
Date: 2023-06-12 18:03:31
LastEditors: thinktanker thinktanker@163.com
LastEditTime: 2024-06-21 16:42:49
FilePath: \sajj\sql.py
Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
'''
import difflib
import logging
import os
import sqlite3
from rapidfuzz import fuzz
# import re
logging.basicConfig(
    format=
    '%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s',
    filename='log.log',
    filemode='a',
    level=logging.DEBUG)
titleList = []
with open('title.txt', 'r', encoding='utf8') as f:
    titleList = f.readlines()
titleCount = (len(titleList))
logging.info('题库答案已载入：{}个'.format(titleCount))
local_path = os.path.dirname(__file__)


def get_equal_rate(str1, str2):
    """
    比较字符串相似度，用来判断选项与答案是否匹配
    :param str1: 字串1
    :param str2: 字串2
    :return: 相似度百分比
    """
    # print(str1, str2)
    return difflib.SequenceMatcher(None, str1, str2).quick_ratio()


# def get_maxRatio_title(txt):
#     test_title = ''
#     for words in txt['words_result']:
#         test_title += words['words']
#     logging.info(test_title)
#     maxRatio = 0
#     maxTitle = ''
#     # index = 0
#     # now = time.time()
#     for title in titleList:
#         ratio = get_equal_rate(test_title, title)
#         # print(ratio)
#         if maxRatio < ratio:
#             maxRatio = ratio
#             maxTitle = title
#     logging.debug('匹配率：{} 题干：{}'.format(maxRatio, maxTitle))
#     return maxTitle.replace('\n', '')


def get_maxRatio_title(input_string):
    # 初始化最大匹配度和索引
    max_match_ratio = 0
    test_title = ''
    # max_match_index = -1
    # comparestr_in_db = ""
    for words in input_string['words_result']:
        test_title += words['words']
    for index, title in enumerate(titleList):
        # 使用fuzz.ratio方法计算两个字符串的匹配度
        match_ratio = fuzz.ratio(test_title, title)
        # 如果当前匹配度大于已记录的最大匹配度，则更新最大匹配度和索引
        if match_ratio > max_match_ratio:
            max_match_ratio = match_ratio
            max_match_index = index
            maxTitle = title
    logging.debug('匹配率：{} 题干：{}'.format(max_match_ratio, maxTitle))
    return maxTitle.replace('\n', '')


def new_search(questionTxt: dict,
               answersTxt: dict,
               text=None,
               answer_text=None,
               autoclick=False,
               check=False):
    x, y = 0, 0
    logging.debug(questionTxt)
    logging.debug(answersTxt)
    answersList = answersTxt["words_result"]
    conn = sqlite3.connect(f"{local_path}{os.sep}sajjtk.db")
    # print(f"{local_path}{os.sep}sajjtk.db")
    cur = conn.cursor()
    if text:
        text.delete('1.0', 'end')
    answer = ""
    question = get_maxRatio_title(questionTxt)
    if text:
        text.insert('insert', question + '\n')
    try:
        sqltxt = f"""SELECT title,a,b,c,d,e,answer FROM sajj WHERE "title" LIKE "%{question}%" """
        cur.execute(sqltxt)
        res = cur.fetchall()
        if res:
            for r in res:
                logging.debug("搜索结果：{}".format(r))
            maxRatio = 0
            answer = ''
            # answer1 = ''
            for i, r in enumerate(res):
                answer_index = int(r[-1])
                # print(answer_index)
                a = r[answer_index]
                for index, _answer in enumerate(answersList):
                    # print(_answer)
                    ratio = get_equal_rate(a, _answer['words'])
                    if maxRatio < ratio:
                        logging.debug("选项：{} 匹配率{}".format(index, ratio))
                        maxRatio = ratio
                        # answer1 = _answer['words']
                        answer = a
                        if autoclick:
                            x = _answer['location']['left']
                            y = _answer['location']['top']
            if not maxRatio:
                answer = '无法匹配，自行判断\n答案：' + (res[0][int(res[0][-1])])
                logging.info(answer)
        else:
            answer += "没有找到"
    except Exception as e:
        logging.error("查询错误：%s".format(e))

    conn.close()
    if answer_text:
        answer_text.delete('1.0', 'end')
        answer_text.insert('insert', answer)
    return x, y


if __name__ == "__main__":
    logging.basicConfig(
        format=
        '%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s',
        filename='log.log',
        filemode='a',
        level=logging.ERROR)
    txt = {
        "words_result": [{
            "words": "第二题"
        }, {
            "words": "《中华人民共和国安全生产法》(2021版)第"
        }, {
            "words": "五条：生产经营单位的庄要负责人是本单位"
        }, {
            "words": "安全生产（)，对本单位的安全生产工作全"
        }, {
            "words": "面负责。其他负责人对职责范围内的安全生"
        }, {
            "words": "产工作负责。"
        }],
        "words_result_num":
        6,
        "log_id":
        1670088818128284268
    }
    answer = {
        "words_result": [{
            "words": "白宇会攻行质房遮",
            "location": {
                "top": 19,
                "left": 202,
                "width": 322,
                "height": 29
            }
        }, {
            "words": "第一责任人",
            "location": {
                "top": 214,
                "left": 230,
                "width": 142,
                "height": 30
            }
        }, {
            "words": "重要责任人",
            "location": {
                "top": 327,
                "left": 230,
                "width": 143,
                "height": 29
            }
        }, {
            "words": "主要责任人",
            "location": {
                "top": 440,
                "left": 231,
                "width": 140,
                "height": 29
            }
        }, {
            "words": "直接责任人",
            "location": {
                "top": 550,
                "left": 231,
                "width": 143,
                "height": 29
            }
        }],
        "words_result_num":
        5,
        "log_id":
        1670088817926640125
    }

    # search(txt, answer, check=True)
    import time
    now = time.time()
    new_search(txt, answer, check=True)
    print(time.time() - now)
